<!--
 * @Descripttion:问卷调查
 * @version:
 * @Author: ada.wu
 * @Date:2024-03-11 11:26:44
 * @LastEditors: ada.wu
 * @LastEditTime: 2024-04-11 16:10:44
-->
<template>
  <div class="bg-white hub">
   <div class="examineInfo-title" v-if="topicInfo.topicText" :class="{'examineInfo-text':topicInfo.topicText!=''}">
      {{topicInfo.topicName}}
      <p v-if="topicInfo.topicText!=''">{{topicInfo.topicText}} </p>
    </div>

    <TopicModuleList v-show="!answerFlag" :topicModuleList="topicModuleList" :examDto="examDto" :disabled="answerFlag"></TopicModuleList>
    <div class="publish" v-show="topicModuleList.length&&!answerFlag">
      <van-button style="" round color="#ffd000" @click="goToNextPage">
        提交
      </van-button>
    </div>
    <template v-if="answerFlag">
      <van-cell class="examineInfo-box" v-for="(item,index) in topicModuleList" :key="index">

        <template #title>
          <div class="p-tb-xs">

            {{index+1}}、{{item.modulesName}}
            <!-- <font v-if="item.isNecessary=='1'" color="#FF3138">*</font>
          {{(index+1)}}.{{item.modulesName}}
          <font color="#979797" v-if="[CHOICE_TYPE.CHOICE].includes(item.choiceType)">【多选】</font> -->
          </div>
        </template>
        <template #label>

          <div v-if="item.choiceType==CHOICE_TYPE.FILL">
            <p class="examineInfo-answer-p">{{item.answerContent}}</p>
          </div>
          <div v-else-if="[CHOICE_TYPE.RADIO].includes(item.choiceType)">
            <van-radio-group v-model="item.optionId" disabled>
              <template v-for="(option,i) in item.moduleOptionList">
                <van-radio :name="option.optionId">
                  {{option.optionsName}}
                  <template #icon="props">
                    <img width="22" class="v-m" :src="props.checked ? getAssets('employee/check.svg') : getAssets('employee/radio.svg')" />
                  </template>
                </van-radio>
                <div v-if="option.remark">{{option.remark}}</div>

              </template>
            </van-radio-group>
          </div>
          <div v-else-if="[CHOICE_TYPE.CHOICE].includes(item.choiceType)">
            <van-checkbox-group v-model="item.optionId" disabled>
              <template v-for="(option,i) in item.moduleOptionList">
                <van-checkbox :name="option.optionId">
                  {{option.optionsName}}
                  <template #icon="props">
                    <img width="22" class="v-m" :src="props.checked ? getAssets('employee/check.svg') : getAssets('employee/radio.svg')" />
                  </template>
                </van-checkbox>
                <div v-if="option.remark">{{option.remark}}</div>
              </template>
            </van-checkbox-group>
          </div>
          <div v-else-if="item.choiceType==CHOICE_TYPE.SCORE" style="padding-left:20px">

            <van-rate readonly :size="30" v-model="item.rateContent" :count="item.moduleOptionList.length" color="#ffd21e" void-icon="star" void-color="#eee" />

            <template v-if="item.moduleOptionList[item.rateContent-1]">
              {{item.moduleOptionList[item.rateContent-1].remark}}
            </template>
          </div>
        </template>
      </van-cell>
    </template>

    <!-- <div class="safe-height p-b-lg"></div> -->
    <!-- <van-cell v-for="(item,index) in displayedExamList" :key="index">
      <template #title>
        {{index+1}}***** {{item.examSubjectAns}}
      </template>
    </van-cell>
 -->
    <!-- <van-cell v-for="(item,index) in topicModuleList" :key="index">
      <template #title>
        {{index+1}}========
        {{item.answerContent}}
        {{item.optionId}}
        {{item.rateContent}}
      </template>
    </van-cell> -->

    <van-empty v-if="topicModuleList.length==0&&!listLoading" description="暂无查询结果…" :image="getAssets('empty.svg')" />
    <!-- <van-dialog v-model:show="disShow" confirmButtonText='返回'>
      <div class="t-c">
        <img src="/@/assets/exam/warning.svg" class="m-t-lg" />
        <div class="text-black t-lx p-b-xs p-t t-c">您的答题过快请您认真答题</div>
        <div class="text-gray  p-b-sm  t-c">打分过快：每页{{examDto.pageQuestion}}个题，必须{{examDto.pageMinTime}}秒</div>
      </div>
    </van-dialog> -->

    <van-dialog v-model:show="equalShow" confirmButtonText='返回'>
      <div class="t-c">
        <img src="/@/assets/exam/warning.svg" class="m-t-lg" />
        <div class="text-black t-lx p-b-xs p-t">您的答题不符合要求，请返回修改后提交</div>
        <div class="text-gray  p-b-sm t-c" v-if="necessaryList.length">
          必答题未完成，题目：{{necessaryList.join(',')}}
        </div>
        <div class="text-gray  p-b-sm t-c" v-for="(npsList,index) in npsList">
          {{npsList}}
        </div>
      </div>
    </van-dialog>
    <van-dialog v-model:show="confirmShow" confirmButtonText='确认提交' cancelButtonText="返回" :showCancelButton="true" @confirm="handelConfirm">
      <div class="t-c">
        <img src="/@/assets/exam/warning.svg" class="m-t-lg" />
        <div class="text-black t-lx p-tb">确认提交无法修改，是否确认</div>
      </div>
    </van-dialog>

    <van-dialog v-model:show="successShow" confirmButtonText='确认' :showCancelButton="false" @confirm="successConfirm">
      <div class="t-c">
        <img src="/@/assets/exam/success.svg" class="m-t-lg" />
        <div class="text-black t-lx p-tb">您已成功提交问卷，谢谢！</div>
      </div>
    </van-dialog>
  </div>
</template>
<script lang="ts">
import { PullRefresh, Divider } from "vant";
import { Checkbox, CheckboxGroup } from "vant";

//util
import { onMounted, reactive, toRefs, ref, nextTick, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PageEnum } from "/@/enums/pageEnum";
import { getNewObj } from "/@/util";
import { formatToDate } from "/@/util/dateUtil";
import moment from "moment";
import TopicModuleList from "./components/topicModuleList.vue";
import ExamConfig from "/@/hooks/examConfig";
import { RadioGroup, Radio } from "vant";

import { useStore } from "/@/store";
//api
import {
  userAnswerQuestionnaire,
  userAnswerQuestionnaireInfo,
  answerResult,
} from "/@/api/ExamApi";
const CHOICE_TYPE = {
  RADIO: "0", //单选
  CHOICE: "1", //多选
  FILL: "2", //填空
  SCORE: "3", //评分
};

export default {
  name: "reservation",
  components: {
    TopicModuleList,
    [Divider.name]: Divider,
    [PullRefresh.name]: PullRefresh,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
  },
  setup() {
    const store = useStore();

    const router = useRouter();
    const route = useRoute();
    let { topicId = "", businessSystem = "", userId = "" } = route.query;

    // 声明响应式状态变量

    const state = reactive({
      CHOICE_TYPE,
      answerFlag: false, //是否选择过了
      showType: false,

      assignBusinessNo: "", //答题开始时间
      answerStartDate: "", //答题开始时间
      topicModuleList: [], //列表
      topicInfo: {
        isJump: "0", //是否允许跳过，1-允许，0-不允许，默认为允许
        isDisplayStatistic: "", //用户是否显示统计，0-不显示统计，1-显示统计
        topicType: "0", //类型，0-问卷，1-投票，2-考试
        topicName: "", //标题
        topicText: "", //描述
        topicPublishMessage: "", //问卷发布消息，如果为空，取消息模板中的内容进行推送
        topicState: "",
        businessType: "", //问卷业务类型  0-个人代理信息收集  1-车险出单信息收集
        assignTarget: [], //指定目标  0-代理人 1-平台所有用户 2-合伙人  3-非S001合伙人（只在S001平台下面展示该选项）           可多选，用英文逗号分隔
        classType: "", //问卷分类 0-通用问卷  1-针对无经验用户[新开]  2-针对有经验用户[老手]
      },

      isQuery: false,
      disNext: false,
      disShow: false,
      confirmShow: false,
      successShow: false,
      equalShow: false,

      queryParam: {
        topicId,
        assignBusinessNo: businessSystem,
        userCode: userId,

        // topicId: "4AC2C8FE251D471F96AA927B2C319373",
        // userCode: "BS100000231",
        // systemCode: "S001",
      },
      necessaryList: <any>[],
      npsList: <any>[],
      //列表接口带过来
      examDto: <any>{},
      listLoading: false,
    });
    onMounted(async () => {
      if (topicId) {
      }
      getExamDetail();

      answerResult({
        ...state.queryParam,
        openapi: true,
      }).then((res: any) => {
        if (res) {
          state.answerFlag = res.answerFlag;
        }
      });
    });

    /**
     * 获取详情
     */
    const getExamDetail = async () => {
      userAnswerQuestionnaireInfo({
        ...state.queryParam,
        // topicId: "4AC2C8FE251D471F96AA927B2C319373",
        // userCode: "BS100000231",
        // systemCode: "S001",
        // assignBusinessNo: "oneplus",
        // wxPicName: "wanJiaYun",
        // isWeChar: "0",
      }).then((res: any) => {
        console.log("res==", res);

        if (res) {
          state.answerStartDate = moment().format("YYYY-MM-DD HH:mm:ss");
          state.topicInfo.isJump = res.isJump;
          state.topicInfo.isDisplayStatistic = res.isDisplayStatistic;
          state.topicInfo.topicType = res.topicType;
          state.topicInfo.topicName = res.topicName;
          state.topicInfo.topicText = res.topicText;
          state.topicInfo.topicPublishMessage = res.topicPublishMessage;
          state.topicInfo.topicState = res.topicState;
          if (res.topicBusinessAssign) {
            state.topicInfo.businessType = res.topicBusinessAssign.businessType;
            state.topicInfo.assignTarget = res.topicBusinessAssign.assignTarget;
            state.topicInfo.classType = res.topicBusinessAssign.classType;
          }
          for (let i in res.topicModuleList) {
            let topicModule = res.topicModuleList[i];
            topicModule.choiceType = `${topicModule.choiceType}`;
            //模块回答问题，当choiceType为2-填空时，必录
            if (typeof topicModule.answerContent == "undefined") {
              topicModule.answerContent = "";
            }
            //选项ID
            topicModule.optionId = "";
            if (topicModule.choiceType == CHOICE_TYPE.CHOICE) {
              //多选值
              topicModule.optionId = [];
            }
            if (topicModule.choiceType == CHOICE_TYPE.SCORE) {
              //星星题
              topicModule.rateContent = "";
            }

            for (let j in topicModule.moduleOptionList) {
              let moduleOption = topicModule.moduleOptionList[j];
              // console.log("moduleOption.isSelected==", moduleOption.isSelected);
              if (moduleOption.isSelected) {
                //有答案的 是否选中
                if (topicModule.choiceType == CHOICE_TYPE.CHOICE) {
                  //多选值
                  topicModule.optionId.push(moduleOption.optionId);
                } else if (topicModule.choiceType == CHOICE_TYPE.RADIO) {
                  //多选值
                  topicModule.optionId = moduleOption.optionId;
                } else if (topicModule.choiceType == CHOICE_TYPE.SCORE) {
                  //星星题
                  topicModule.rateContent = parseInt(j) + 1;
                }
              } else {
                moduleOption.isSelected = false;
              }
            }
          }
          state.topicModuleList = res.topicModuleList;
        }
      });
    };

    // 跳转到下一页
    function goToNextPage() {
      if (!getCheck()) {
        state.confirmShow = true;
      }
    }

    // 跳转到上一页
    function getCheck() {
      let flag = false;
      state.npsList = [];
      state.necessaryList = [];
      let npsList = [] as any;
      state.topicModuleList.forEach((item: any, index: any) => {
        if (item.isNecessary == "1") {
          //填空
          if ([CHOICE_TYPE.FILL].includes(item.choiceType)) {
            if (!item.answerContent) {
              state.necessaryList.push(index + 1);
            }
          } else if ([CHOICE_TYPE.RADIO].includes(item.choiceType)) {
            if (!item.optionId) {
              state.necessaryList.push(index + 1);
            }
          } else if ([CHOICE_TYPE.CHOICE].includes(item.choiceType)) {
            if (item.optionId.length == 0) {
              state.necessaryList.push(index + 1);
            }
          } else if ([CHOICE_TYPE.SCORE].includes(item.choiceType)) {
            if (!item.rateContent) {
              state.necessaryList.push(index + 1);
            }
          }
        }
        //单选选择了
        if ([CHOICE_TYPE.RADIO].includes(item.choiceType) && item.optionId) {
          // canInput 是否填空  1:是;0 或空/非填空  inputFlag 填空是否必填，1:必填;0 非必填
          for (let j in item.moduleOptionList) {
            let { canInput, inputFlag, optionId, remark, optionsName } =
              item.moduleOptionList[j];
            if (item.optionId == optionId) {
              if (canInput == "1" && inputFlag == "1") {
                if (!remark) {
                  state.npsList.push(
                    "第" + (1 * index + 1) + "题:" + optionsName + "没有录入"
                  );
                }
              }
            }
          }
        } else if (
          [CHOICE_TYPE.CHOICE].includes(item.choiceType) &&
          item.optionId.length
        ) {
          for (let j in item.moduleOptionList) {
            let { canInput, inputFlag, optionId, remark, optionsName } =
              item.moduleOptionList[j];
            if (item.optionId.includes(optionId)) {
              if (canInput == "1" && inputFlag == "1") {
                if (!remark) {
                  state.npsList.push(
                    "第" + (1 * index + 1) + "题:" + optionsName + "没有录入"
                  );
                }
              }
            }
          }
        }
      });
      state.equalShow = false;
      if (state.necessaryList.length > 0 || state.npsList.length > 0) {
        state.equalShow = true;
        flag = true;
      }

      return flag;
    }

    //获取答案
    const getAnswers = () => {
      //组装答案
      let topicAnswerList = [];
      for (let i in state.topicModuleList) {
        let topicModule = state.topicModuleList[i] as any;
        let params = {
          moduleId: topicModule.moduleId,
          choiceType: topicModule.choiceType,
          answerContent: topicModule.answerContent || "",
          optionInfos: [],
        };
        //单选
        let selectedOption = [];
        if ([CHOICE_TYPE.RADIO].includes(topicModule.choiceType)) {
          selectedOption = topicModule.moduleOptionList.filter(
            (moduleOption: any) =>
              moduleOption.optionId === topicModule.optionId
          );
        } else if ([CHOICE_TYPE.CHOICE].includes(topicModule.choiceType)) {
          selectedOption = topicModule.moduleOptionList.filter(
            (moduleOption: any) =>
              topicModule.optionId.includes(moduleOption.optionId)
          );
        } else if ([CHOICE_TYPE.SCORE].includes(topicModule.choiceType)) {
          console.log(`${topicModule.rateContent}`)
          if (`${topicModule.rateContent}`) {
            let index = parseInt(`${topicModule.rateContent}`);
            selectedOption = [topicModule.moduleOptionList[index - 1]];
          }
        }

console.log('selectedOption==',selectedOption)
        if (selectedOption && selectedOption.length) {
          selectedOption.forEach(({ optionId, remark }) => {
            params.optionInfos.push({ optionId, remark });
          });
        }

        topicAnswerList.push(params);
      }
      return topicAnswerList;
    };
    //试卷回答
    const handelAnswerExam = (_status = "") => {
      return new Promise(function (resolve, reject) {
        if (_status) {
          let model = {
            userCode: userId,
            topicId,
            answerStartDate: state.answerStartDate,
            assignBusinessNo: businessSystem,
            topicAnswerList: getAnswers(),
          };

          userAnswerQuestionnaire({ ...model })
            .then((res) => {
              resolve(true);
            })
            .catch(() => {
              resolve(false);
            });
        }
      });
    };
    async function handelConfirm() {
      let res = await handelAnswerExam("3");
      if (res) state.successShow = true;
    }
    function successConfirm() {
      window.parent.postMessage(
        { action: "userAnswerQuestion", data: "success" },
        "*"
      );
    }
    return {
      ...toRefs(state),
      goToNextPage,
      handelConfirm,
      handelAnswerExam,
      successConfirm,
    };
  },
};
</script>

<style lang="scss" scoped>
::v-deep(.van-radio) {
  padding-bottom: 10px;
  &:last-child {
    padding-bottom: 0;
  }
}
::v-deep(.van-radio__label) {
  color: #555555 !important;
}
::v-deep(.van-radio__icon) {
  height: 22px;
}
::v-deep(.van-checkbox) {
  padding-bottom: 10px;
  &:last-child {
    padding-bottom: 0;
  }
}
::v-deep(.van-checkbox__label) {
  color: #555555 !important;
}
::v-deep(.van-checkbox__icon) {
  height: 22px;
}
::v-deep(.van-cell__title) {
  font-weight: 500;
  font-size: 16px;
  color: #262626;
}
::v-deep(.van-cell__label) {
  font-weight: 400;
  font-size: 16px;
  color: #555555;
  padding-bottom: 20px;
}
.hub {
  max-width: 750px;
  margin: 0 auto;
}
// .publish {
//   max-width: 750px;
//   left: 0;
//   right: 0;
// }
::v-deep(.van-cell) {
  align-items: center;
}
.publish {
  width: 80%;
  max-width: 240px;
  margin: 0 auto;
  .back {
    background: #fffdf3 !important;
  }
  .van-button--round {
    font-weight: 500 !important;
    font-size: 14px !important;
    color: #1a1446 !important;
    width: 100%;
  }
}

.examineInfo-title {
  color: #2e3942;
  font-size: 23px;
  font-weight: bold;
  padding: 15px 30px;
  text-align: left;
  font-size: 20px;
  margin-bottom: 15px;
  box-sizing: border-box;
  background: #ffffff url("/@/assets/exam/banner2.png") no-repeat left top;

  background-size: 100% 100%;
  height: 7vh;

  p {
    font-weight: 400;
    font-size: 12px;
    color: #2c3d4a;
    padding-top: 15px;
    padding-right: 40%;
  }
}

.examineInfo-title.examineInfo-text {
  background: #ffffff url("/@/assets/exam/banner1.png") no-repeat left top;
  background-size: cover !important;
  height: 16vh;
}

@media screen and (min-width: 761px) {
  .examineInfo-title.examineInfo-text {
    height: 27vh;
  }

  .examineInfo-title {
    font-size: 26px;
  }
}

@media screen and (max-width: 760px) {
  .examineInfo-title.examineInfo-text {
    height: 27vh;
  }
}

@media screen and (max-width: 600px) {
  .examineInfo-title.examineInfo-text {
    height: 24vh;
  }
}

@media screen and (max-width: 500px) {
  .examineInfo-title.examineInfo-text {
    height: 20vh;
  }
}

@media screen and (max-width: 430px) {
  .examineInfo-title.examineInfo-text {
    height: 18vh;
  }
}

@media screen and (max-width: 414px) {
  .examineInfo-title.examineInfo-text {
    height: 18vh;
  }
}

@media screen and (max-width: 390px) {
  .examineInfo-title.examineInfo-text {
    height: 18vh;
  }
}

@media screen and (max-width: 375px) {
  .examineInfo-title.examineInfo-text {
    height: 20vh;
  }
}

@media screen and (max-width: 360px) {
  .examineInfo-title.examineInfo-text {
    height: 20vh;
  }
}

@media screen and (max-width: 320px) {
  .examineInfo-title.examineInfo-text {
    height: 18vh;
  }
}
</style>
